
import os
import os.path

filname = "学生成绩文件.txt"

def main():
    while True:
        menum()
        num = int(input("请输入数字："))
        if num in [1, 2, 3, 4, 5, 6, 7, 0]:
            if num == 0:
                answer = input("你确定要退出系统么 Y/N")
                if answer == 'Y' or answer == 'y':
                    print("谢谢你的使用！！")
                    break
                else:
                    continue
            elif num == 1:
                insert()
            elif num == 2:
                search()
            elif num == 3:
                delete()
            elif num == 4:
                modify()
            elif num == 5:
                sort()
            elif num == 6:
                total()
            elif num == 7:
                show()
        else:
            print("输入选项不在范围内，请重新选择！")
    return

def menum():
    print(" 学生信息管理系统 ".center(60, '='))
    print(" 功能菜单".rjust(38, "-"), "-------------------------")
    print("1.录入学生信息".rjust(30, " "))
    print("2.查找学生信息".rjust(30, " "))
    print("3.删除学生信息".rjust(30, " "))
    print("4.修改学生信息".rjust(30, " "))
    print("5.排序".rjust(26, " "))
    print("6.统计学生人数".rjust(30, " "))
    print("7.显示学生信息".rjust(30, " "))
    print("0.退出学生系统".rjust(30, " "))
    print("-".center(68, "-"))


# 录入学生信息
def insert():
    student_list = []
    while True:
        ID = input("请输入你的学号：")
        if not ID:
            break
        name = input("请输入你的姓名：")
        if not name:
            break
        try:
            C = float(input("请输入你的C语言成绩："))
            Python = float(input("请输入你的Python成绩："))
            shujujiegou = float(input("请输入你的数据结构成绩："))
        except:
            print("输入的不是数字,请重新输入：")
            continue
        student = {'学号': ID, '姓名': name, 'C语言': C, 'Python': Python, '数据结构': shujujiegou}
        student_list.append(student)
        answer = input("你是否继续添加学生信息Y/N: ")
        if answer == 'Y' or answer == 'y':
            continue
        else:
            break

    save(student_list)
    print("学生信息录入完毕！")


# 学生信息存入文件
def save(lst):
    try:
        life = open(filname, 'a', encoding='gbk')
        #life.write('\n')
    except:
        life = open(filname, 'w', encoding='gbk')
    for item in lst:
        life.write(str(item)+"\n")
    life.close()


# 查找学生信息
def search():
    student_quert = []
    while True:
        answer = input("按ID查找请输入1，按姓名查找请输入2：")
        if answer == '1':
            student_id = input("请输入学生ID：")
        elif answer == '2':
            student_name = input("请输入学生姓名：")
        else:
            print("你输入的信息有误，请重新输入")
            search()
        with open(filname, 'r', encoding='gbk') as rfile:
            student_old = rfile.readlines()
            for item in student_old:
                d = dict(eval(item))
                if student_id != '':
                    if d['学号'] == student_id:
                        student_quert.append(d)
                elif student_name != '':
                    if d['姓名'] == student_name:
                        student_quert.append(d)
        show_student(student_quert)
        student_quert.clear()
        answer = input('是否继续查询? Y/N:')
        if answer == 'Y' or answer == 'y':
            continue
        else:
            break

def show_student(lst):
    if len(lst) == 0:
        print("没有查询到学生信息，无数据显示！")
        return
    format_title = '{:^6}{:^8}{:^8}{:^9}{:^0}{:^12}'
    print(format_title.format('学号', '姓名', 'C语言', 'Python', '数据结构', '总成绩'))
    format_data = '{:^8}{:^10}{:^6}{:^9}{:^9}{:^10}'
    for item in lst:
        print(format_data.format(item.get('学号'),
                                 item.get('姓名'),
                                 item.get('C语言'),
                                 item.get('Python'),
                                 item.get('数据结构'),
                                 int(item.get('C语言'))+int(item.get('Python'))+int(item.get('数据结构'))))


# 删除学生信息
def delete():
    while True:
        student_id = input("请输入要删除的学生ID；")
        if student_id != '':
            if os.path.exists(filname):    #判断文件是否存在
                with open(filname, 'r', encoding='gbk') as file:
                    student_old = file.readlines()
            else:
                student_old = []
            flag = False    #标记是否删除
            if student_old:
                with open(filname, 'w', encoding='gbk')as wfile:
                    d = {}
                    for item in student_old:
                        d = dict(eval(item))
                        if d['学号'] != student_id:
                            wfile.write(str(d)+'\n')
                        else:
                            flag = True  # ID 已删除
                    if flag:
                        print("id为{0}的学生信息已经删除！".format(student_id))
                    else:
                        print(f"id为{student_id}的学生信息不存在！")
            else:
                print("无存储学生信息！")
                break
            show()
            answer = input("是否继续删除学生信息 Y/N: ")
            if answer == 'Y' or answer == 'y':
                continue
            else:
                break
        else:
            continue


# 修改学生信息
def modify():
    show()
    while True:
        if os.path.exists(filname):
            with open(filname, 'r', encoding="gbk") as file:
                student_old = file.readlines()
        else:
            return
        student_id = input("请输入要修改的学生ID：")
        if student_id == '':
            print("请重新输入：")
            continue
        with open(filname, 'w', encoding='gbk')as wfile:
            for item in student_old:
                d = dict(eval(item))
                if d['学号'] == student_id:
                    print('找到学生信息了，可以修改他的相关信息了！')
                    while True:
                        try:
                            d['姓名'] = input("请输入学生姓名")
                            d['C语言'] = float(input("请输入你的C语言成绩："))
                            d['Python'] = float(input("请输入你的Python成绩："))
                            d['数据结构'] = float(input("请输入你的数据结构成绩："))
                        except:
                            print("输入的不是数字,请重新输入：")
                        else:
                            break
                    wfile.write(str(d)+'\n')
                    print("修改成功！")
                else:
                    wfile.write(str(d)+'\n')
            answer = input("是否要继续修改学生信息 Y/N：")
            if answer == 'y' or answer == 'Y':
                continue
            else:
                break


# 排序
def sort():
    show()
    if os.path.exists(filname):
        with open(filname,'r',encoding='gbk') as rfile:
            student_old = rfile.readlines()
        student_new=[]
        for item in student_old:
            d = dict(eval(item))
            student_new.append(d)
    else:
        print("文件名不存在！")
        return
    asc_or_desc = input("请选择(1 降序/0 升序):")
    if asc_or_desc == '1':    #降序
        asc_or_desc_bool = True
    elif asc_or_desc == '0':  #升序
        asc_or_desc_bool = False
    else:
        print("你的输入有误，请重新输入！")
        sort()
    mode = input("请选择要排序方式(1.C语言 2.Python 3.数据结构 4.总成绩)：")
    if mode == '1':
        student_new.sort(key=lambda x:int(x['C语言']), reverse=asc_or_desc_bool)
    elif mode == '2':
        student_new.sort(key=lambda x:int(x['Python']), reverse=asc_or_desc_bool)
    elif mode == '3':
        student_new.sort(key=lambda x:int(x['数据结构']), reverse=asc_or_desc_bool)
    elif mode == '4':
        student_new.sort(key=lambda x:int(x['C语言'])+int(x['Python'])+int(x['数据结构']), reverse=asc_or_desc_bool)
    else:
        print("输入的信息有误，请重新输入！")
        sort()
    show_student(student_new)


# 统计学生人数
def total():
    if os.path.exists(filname):
        with open(filname,'r',encoding='gbk') as rfile:
            student_old = rfile.readlines()
            if student_old != '':
                print("一共%d个学生信息！"%(len(student_old)))
            else:
                print("没有录入学生信息")
    else:
        print("学生存储文件不存在")


# 显示学生信息
def show():
    student_quert = []
    if os.path.exists(filname):
        with open(filname,'r',encoding='gbk') as rfile:
            student_old = rfile.readlines()
        for item in student_old:
            student_quert.append(eval(item))
        if student_quert:
            show_student(student_quert)
    else:
        print("学生存储文件不存在")


if __name__ == '__main__':
    main()
